package com.zzyl.serve.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.serve.domain.DeviceData;
import com.zzyl.serve.service.impl.DeviceDataServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.qpid.jms.*;
import org.apache.qpid.jms.message.JmsInboundMessageDispatch;
import org.apache.qpid.jms.transports.TransportOptions;
import org.apache.qpid.jms.transports.TransportSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.jms.*;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author liuyp
 * @since 2025/8/19
 */
@Slf4j
@Component
public class AmqpListener implements ApplicationRunner {
    @Autowired
    private HuaWeiIotConfigProperties properties;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private DeviceDataServiceImpl deviceDataService;

    private static String clientId;
    static {
        try {
            clientId = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    /**
     * 当前bean对象被创建并放到IoC容器后 会立即自动执行的方法
     * 注意：
     *	当前bean是默认的单例bean，在IoC容器创建后会立即创建此对象
     *  而IoC容器在运行启动类启动服务时就创建
     *	即：当前方法会在服务启动时立即自动执行
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        start();
    }

    private void start() throws Exception {
        for (int i = 0; i < properties.getConnectionCount(); i++) {
            //1. 创建连接
            //1.1 拼接连接地址
            String connectionUrl = generateConnectUrl();
            //1.2 创建连接对象
            Connection connection = createConnection(connectionUrl);
            //1.3 添加连接监听器：当建立连接、断开连接等等状态变化时会监听到
            ((JmsConnection)connection).addConnectionListener(jmsConnectionListener);
            //1.4 创建 Session, Session.CLIENT_ACKNOWLEDGE: 收到消息后，需要手动调用message.acknowledge()。Session.AUTO_ACKNOWLEDGE: SDK自动ACK（推荐）。
            Session session = connection.createSession(false, properties.isAutoAcknowledge() ? Session.AUTO_ACKNOWLEDGE : Session.CLIENT_ACKNOWLEDGE);
            connection.start();

            //2. 启动监听
            //2.1 创建消费者
            MessageConsumer consumer = session.createConsumer(new JmsQueue(properties.getQueueName()));
            //2.2 监听队列中的消息
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    //将消息交给线程池进行异步处理
                    threadPoolTaskExecutor.submit(() -> processMessage(message));
                }
            });
        }
    }

    /**
     * 处理消息的方法
     * @param message 消息对象
     */
    private void processMessage(Message message) {
        String content = null;
        try {
             content = message.getBody(String.class);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            log.info("receive message,\n topic = {},\n messageId = {},\n content = {}", topic, messageId, content);
        } catch (JMSException e) {
            throw new BaseException("服务器错误");
        }

        JSONObject jsonObject = JSONUtil.parseObj(content);
        JSONObject notifyData = jsonObject.getJSONObject("notify_data");
        if(notifyData==null){
            return;
        }
        IotMsgNotifyData iotMsgNotifyData = JSONUtil.toBean(notifyData, IotMsgNotifyData.class);
        if (iotMsgNotifyData.getHeader()==null||iotMsgNotifyData.getBody()==null|| ObjectUtil.isEmpty(iotMsgNotifyData.getBody().getServices())){
            return;
        }
        deviceDataService.batchSaveDeviceData(iotMsgNotifyData);

    }

    /**连接监听器*/
    private final JmsConnectionListener jmsConnectionListener = new JmsConnectionListener() {
        /**
         * 连接成功建立。
         */
        @Override
        public void onConnectionEstablished(URI remoteURI) {
            log.info("onConnectionEstablished, remoteUri:{}", remoteURI);
        }

        /**
         * 尝试过最大重试次数之后，最终连接失败。
         */
        @Override
        public void onConnectionFailure(Throwable error) {
            log.error("onConnectionFailure, {}", error.getMessage());
        }

        /**
         * 连接中断。
         */
        @Override
        public void onConnectionInterrupted(URI remoteURI) {
            log.info("onConnectionInterrupted, remoteUri:{}", remoteURI);
        }

        /**
         * 连接中断后又自动重连上。
         */
        @Override
        public void onConnectionRestored(URI remoteURI) {
            log.info("onConnectionRestored, remoteUri:{}", remoteURI);
        }

        @Override
        public void onInboundMessage(JmsInboundMessageDispatch envelope) {
        }

        @Override
        public void onSessionClosed(Session session, Throwable cause) {
        }

        @Override
        public void onConsumerClosed(MessageConsumer consumer, Throwable cause) {
        }

        @Override
        public void onProducerClosed(MessageProducer producer, Throwable cause) {
        }
    };

    private Connection createConnection(String connectionUrl) throws Exception {
        JmsConnectionFactory cf = new JmsConnectionFactory(connectionUrl);
        TransportOptions to = new TransportOptions();
        to.setTrustAll(true);
        cf.setSslContext(TransportSupport.createJdkSslContext(to));
        String userName = "accessKey=" + properties.getAccessKey();
        cf.setExtension(JmsConnectionExtensions.USERNAME_OVERRIDE.toString(), (connection, uri) -> {
            // IoTDA的userName组成格式如下：“accessKey=${accessKey}|timestamp=${timestamp}”
            String newUserName = userName;
            if (connection instanceof JmsConnection) {
                newUserName = ((JmsConnection) connection).getUsername();
            }
            return newUserName + "|timestamp=" + System.currentTimeMillis();
        });
        // 创建连接
        return cf.createConnection(userName, properties.getAccessCode());
    }

    public String generateConnectUrl() {
        String uri = MessageFormat.format("{0}://{1}:{2}", (properties.isUseSsl() ? "amqps" : "amqp"), properties.getHost(), String.valueOf(properties.getPort()));
        Map<String, String> uriOptions = new HashMap<>();
        uriOptions.put("amqp.vhost", properties.getVhost());
        uriOptions.put("amqp.idleTimeout", String.valueOf(properties.getIdleTimeout()));
        uriOptions.put("amqp.saslMechanisms", properties.getSaslMechanisms());

        Map<String, String> jmsOptions = new HashMap<>();
        jmsOptions.put("jms.prefetchPolicy.queuePrefetch", String.valueOf(properties.getQueuePrefetch()));
        if (StringUtils.isNotEmpty(clientId)) {
            jmsOptions.put("jms.clientID", clientId);
        } else {
            jmsOptions.put("jms.clientID", UUID.randomUUID().toString());
        }
        jmsOptions.put("failover.reconnectDelay", String.valueOf(properties.getReconnectDelay()));
        jmsOptions.put("failover.maxReconnectDelay", String.valueOf(properties.getMaxReconnectDelay()));
        if (properties.getMaxReconnectAttempts() > 0) {
            jmsOptions.put("failover.maxReconnectAttempts", String.valueOf(properties.getMaxReconnectAttempts()));
        }
        if (properties.getExtendedOptions() != null) {
            for (Map.Entry<String, String> option : properties.getExtendedOptions().entrySet()) {
                if (option.getKey().startsWith("amqp.") || option.getKey().startsWith("transport.")) {
                    uriOptions.put(option.getKey(), option.getValue());
                } else {
                    jmsOptions.put(option.getKey(), option.getValue());
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(uriOptions.entrySet().stream()
                .map(option -> MessageFormat.format("{0}={1}", option.getKey(), option.getValue()))
                .collect(Collectors.joining("&", "failover:(" + uri + "?", ")")));
        stringBuilder.append(jmsOptions.entrySet().stream()
                .map(option -> MessageFormat.format("{0}={1}", option.getKey(), option.getValue()))
                .collect(Collectors.joining("&", "?", "")));
        return stringBuilder.toString();
    }
}